package com.greenantmall.service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVQuery.CachePolicy;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.R;
import com.greenantmall.activity.fragment.OrdersListFragment;
import com.greenantmall.bean.AntAVObject;
import com.greenantmall.bean.Banners;
import com.greenantmall.bean.EMCompany;
import com.greenantmall.bean.EMRecv;
import com.greenantmall.bean.Evaluate;
import com.greenantmall.bean.Goods;
import com.greenantmall.bean.GoodsKind;
import com.greenantmall.bean.GoodsList;
import com.greenantmall.bean.GoodsRecommend;
import com.greenantmall.bean.GoodsStyles;
import com.greenantmall.bean.HotWords;
import com.greenantmall.bean.MyFavorite;
import com.greenantmall.bean.MyMsg;
import com.greenantmall.bean.Order;
import com.greenantmall.bean.OrderItem;
import com.greenantmall.bean.OrderList;
import com.greenantmall.bean.OrderStatusCode;
import com.greenantmall.bean.RecommendByUs;
import com.greenantmall.bean.ServerSection;
import com.greenantmall.bean.ServiePhone;
import com.greenantmall.bean.ShippingAddr;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.StoreInfo;
import com.greenantmall.bean.TradeStyle;
import com.greenantmall.bean.UIBanners;
import com.greenantmall.bean.UIGoods;
import com.greenantmall.bean.UIGoodsCategory;
import com.greenantmall.bean.UIGoodsList;
import com.greenantmall.bean.UIGoodsRecommend;
import com.greenantmall.bean.UIRecommendByUs;
import com.greenantmall.bean.VersionInfo;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.NotificationUtil;
import com.greenantmall.utils.UtilTools;
import com.greenantmall.utils.iLog;

public class RetrieveDataAsyn {
	private static RetrieveDataAsyn sInstance;
	private final String TAG = "RetrieveDataAsyn";

	private ExecutorService mExecutorService = Executors.newCachedThreadPool();
	private Handler mHandler = new Handler(Looper.getMainLooper());

	private boolean isInit = false;

	private RetrieveDataAsyn() {

	}

	public static RetrieveDataAsyn getInstance() {
		if (sInstance == null) {
			synchronized ("") {
				if (sInstance == null) {
					sInstance = new RetrieveDataAsyn();
				}
			}
		}
		return sInstance;
	}

	public void avInit(Context ctx) {
		AVOSCloud.initialize(ctx, "ak17uowdqweoh18wn56qe5crtikhr3wzjv8751xo37m2f8o6",
				"x8xa025tojekkbx69fmt7m6h1jh4zrhhfu5psepi82890g8e");

		 AVAnalytics.enableCrashReport(ctx, true);
	        AVOSCloud.setLastModifyEnabled(true);
	        AVOSCloud.setDebugLogEnabled(true);

	}

	public void registerAVClass(Context ctx) {
		// AVOSCloud.setDebugLogEnabled(true);
		// AVAnalytics.enableCrashReport(ctx, true);
		AVObject.registerSubclass(Goods.class);
		AVObject.registerSubclass(GoodsKind.class);
		AVObject.registerSubclass(GoodsStyles.class);
		AVObject.registerSubclass(TradeStyle.class);
		AVObject.registerSubclass(Banners.class);
		AVObject.registerSubclass(RecommendByUs.class);
		AVObject.registerSubclass(GoodsRecommend.class);
		AVObject.registerSubclass(ServerSection.class);
		AVObject.registerSubclass(MyFavorite.class);
		AVObject.registerSubclass(ShoppingCart.class);
		AVObject.registerSubclass(ShippingAddr.class);
		AVObject.registerSubclass(StoreInfo.class);
		AVObject.registerSubclass(Order.class);
		AVObject.registerSubclass(ServiePhone.class);
		AVObject.registerSubclass(Evaluate.class);
		AVObject.registerSubclass(VersionInfo.class);
		AVObject.registerSubclass(HotWords.class);
		AVObject.registerSubclass(EMRecv.class);
		AVObject.registerSubclass(EMCompany.class);

		// 消息通知注册
		try {
			AVInstallation.getCurrentInstallation().save();
			AntHomeApplication.installationId = AVInstallation.getCurrentInstallation().getInstallationId();
		} catch (AVException e) {
			e.printStackTrace();
		}
		isInit = true;
		Log.d(TAG, "installationId:" + AntHomeApplication.installationId);
	}

	private void checkIsInit() {
		if (!isInit) {
			avInit(AntHomeApplication.context);
			registerAVClass(AntHomeApplication.context);
		}
	}

	public void getServiePhone(final int requestId, final RetrieveDataListener listener) {
		Log.d("CEXX", "CEXX ---> getServiePhone");
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				ServiePhone serviePhone = null;

				AVQuery<ServiePhone> query = AVQuery.getQuery(ServiePhone.class);
				try {
					serviePhone = query.getFirst();
				} catch (AVException e) {
					e.printStackTrace();
					Log.d("CEXX", "CEXX ---> getServiePhone ---> e : " + e.toString());
				}

				final ServiePhone result = serviePhone;
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, result);
					}
				});
			}
		});
	}

	public void getBanners(final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				ServerSection serverSection = UtilTools.getServerSection(AntHomeApplication.context);
				final List<Banners> antBanners = new ArrayList<Banners>();

				AVQuery<Banners> query = AVQuery.getQuery(Banners.class);

				AVQuery<ServerSection> innerQuery = AVQuery.getQuery(ServerSection.class);
				innerQuery.whereEqualTo(ServerSection.ATTR_OBJECID, serverSection.getObjectId());
				query.whereMatchesQuery(Goods.ATTR_UPTOWNS, innerQuery);

				query.orderByDescending("updatedAt");
				query.limit(1000);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					antBanners.addAll(query.find());

					for (int i = 0; i < antBanners.size(); i++) {
						try {
							Banners banners = antBanners.get(i);

							AVRelation<Goods> relationGoods = banners.getRelation(Banners.ATTR_LIST);
							AVQuery<Goods> queryGoods = relationGoods.getQuery();

							queryGoods.whereMatchesQuery(Goods.ATTR_UPTOWNS, innerQuery);
							queryGoods.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
							banners.getGoodsList().addAll(queryGoods.find());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} catch (AVException exception) {
					iLog.e(TAG, "Query AntBanners failed.", exception);
				}

				final List<UIBanners> uiBannersList = new ArrayList<UIBanners>();
				for (Banners banners : antBanners) {
					UIBanners uiBanners = new UIBanners();
					uiBanners.setPosterUrl(banners.getFileUrl());
					List<UIGoods> uiGoodsList = new ArrayList<UIGoods>();
					List<Goods> goodsList = banners.getGoodsList();
					if (goodsList != null) {
						for (Goods goods : goodsList) {
							UIGoods ug = new UIGoods();
							ug.setStoreId(goods.getStoreId());
							ug.setObjectId(goods.getObjectId());
							ug.setDescroption(goods.getDescription());
							ug.setSpecs(goods.getSpecs());
							ug.setDiscount(goods.getDiscount());
							ug.setPicUrl(goods.getImageUrl());
							ug.setPriceAfterDiscount(goods.getRealPrice());
							ug.setShowTag(goods.getShowTag());
							ug.setUnit(goods.getUnit());
							ug.setStepUnit(goods.getWeighUnit());
							ug.setStep(goods.getWeighStep());
							ug.setPriceBeforeDiscount(goods.getPrice());
							ug.setPriceByWeight(goods.isWeighAble());
							ug.setBuyedPeopleCount(goods.getTotalSales());
							ug.setStock(goods.getStock());
							uiGoodsList.add(ug);
						}
					}
					uiBanners.setUIGoodsList(uiGoodsList);
					uiBannersList.add(uiBanners);
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, uiBannersList);
					}
				});
			}
		});
	}

	public void getTradeStyle(final int sectionNum, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				final List<TradeStyle> antTradeStyles = new ArrayList<TradeStyle>();
				;

				AVQuery<TradeStyle> query = AVQuery.getQuery(TradeStyle.class);
				query.whereEqualTo(TradeStyle.ATTR_SECTIONNUM, sectionNum);
				query.orderByAscending("showIndex");
				query.include(TradeStyle.ATTR_GOODSSTYLELIST);
				query.limit(100);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					antTradeStyles.addAll(query.find());
				} catch (AVException exception) {
					Log.e(TAG, "Query AntTradeStyle failed.", exception);
				}

				if (antTradeStyles != null && antTradeStyles.size() > 0) {
					for (int i = 0; i < antTradeStyles.size(); i++) {
						TradeStyle tempTrade = antTradeStyles.get(i);
						AVRelation<GoodsStyles> relation = tempTrade.getRelation(TradeStyle.ATTR_GOODSSTYLELIST);
						AVQuery<GoodsStyles> query1 = relation.getQuery();
						try {
							tempTrade.setGoodsStylesList(query1.find());
						} catch (AVException e) {
							e.printStackTrace();
						}
					}

				}

				final List<UIGoodsCategory> goodsCategoryList = new ArrayList<UIGoodsCategory>();
				for (TradeStyle tradeStyle : antTradeStyles) {
					UIGoodsCategory goodsCategory = new UIGoodsCategory();
					goodsCategory.setName(tradeStyle.getName());
					goodsCategory.setObjectId(tradeStyle.getObjectId());
					goodsCategory.setPicUrl(tradeStyle.getFileUrl());
					goodsCategory.setShowIndex(tradeStyle.getShowIndex());
					goodsCategory.setUserId(tradeStyle.getUserId());
					goodsCategory.setGoodsStylesList(tradeStyle.getGoodsStylesList());
					goodsCategory.setShowStyle(tradeStyle.getShowStyle());
					goodsCategoryList.add(goodsCategory);
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, goodsCategoryList);
					}
				});
			}
		});
	}

	public void getGoodsRecommend(final int sectionNum, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				final List<GoodsRecommend> list = new ArrayList<GoodsRecommend>();

				AVQuery<GoodsRecommend> query = AVQuery.getQuery(GoodsRecommend.class);
				query.orderByDescending("updatedAt");
				query.whereEqualTo(GoodsRecommend.ATTR_SECTIONNUM, sectionNum);
				query.limit(1000);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					list.addAll(query.find());
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {

						AVRelation<Goods> relation = list.get(i).getRelation(GoodsRecommend.ATTR_LIST);
						AVQuery<Goods> query1 = relation.getQuery();
						try {
							query1.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
							List<Goods> temp = query1.find();
							if (temp != null && temp.size() > 0) {
								list.get(i).setGoods(temp.get(0));
							}
						} catch (AVException e) {
							e.printStackTrace();
						}
					}
				}

				final List<UIGoodsRecommend> ugrList = new ArrayList<UIGoodsRecommend>();
				for (GoodsRecommend gr : list) {
					UIGoodsRecommend ugr = new UIGoodsRecommend();
					ugr.setPicUrl(gr.getImageUrl());
					ugr.setShowIndex(gr.getShowIndex());
					ugr.setShowStyle(gr.getImageStyle());
					ugr.setObjectId(gr.getObjectId());
					ugr.setStoreId(gr.getStoreId());
					if (gr.getGoods() != null) {
						ugr.setGoodsObjectId(gr.getGoods().getObjectId());
						ugr.setShowTag(gr.getGoods().getShowTag());
						ugr.setGoods(gr.getGoods());
					}
					ugrList.add(ugr);
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, ugrList);
					}
				});
			}
		});
	}

	/**
	 * GoodsListActivity from HomePageImageItems
	 * 
	 * @param goodsRecomendObjectId
	 * @param orderBy
	 *            :按照排序0，销量；1：价格；2：更新时间
	 */
	public void getGoodsListByGoodsRecommendObjectId(final String goodsRecomendObjectId, final int orderBy,
			final int start, final int expectedCount, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				List<Goods> tempGoodsList = null;
				int totalNum = 0;
				try {
					AVQuery<GoodsRecommend> query = AVQuery.getQuery(GoodsRecommend.class);
					query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
					GoodsRecommend goodsRecommend = query.get(goodsRecomendObjectId);
					AVRelation<Goods> avRelation = goodsRecommend.getRelation(GoodsRecommend.ATTR_LIST);
					AVQuery<Goods> avQuery = avRelation.getQuery();
					avQuery.skip(start);
					avQuery.limit(expectedCount);
					avQuery.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
					if (orderBy == 1) {
						avQuery.orderByAscending(Goods.ATTR_PRICE);
					} else if (orderBy == 2) {
						avQuery.orderByDescending(Goods.ATTR_UPDATE_AT);
					} else {
						avQuery.orderByDescending(Goods.ATTR_TOTAL_SALES);
					}
					avQuery.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
					tempGoodsList = avQuery.find();
					totalNum = avQuery.count();
				} catch (Exception e) {
					e.printStackTrace();
				}

				List<UIGoods> goodsList = new ArrayList<UIGoods>();
				for (Goods goods : tempGoodsList) {
					UIGoods ug = new UIGoods();
					ug.setStoreId(goods.getStoreId());
					ug.setObjectId(goods.getObjectId());
					ug.setDescroption(goods.getDescription());
					ug.setSpecs(goods.getSpecs());
					ug.setDiscount(goods.getDiscount());
					ug.setPicUrl(goods.getImageUrl());
					ug.setPriceAfterDiscount(goods.getRealPrice());
					ug.setShowTag(goods.getShowTag());
					ug.setUnit(goods.getUnit());
					ug.setStepUnit(goods.getWeighUnit());
					ug.setStep(goods.getWeighStep());
					ug.setPriceBeforeDiscount(goods.getPrice());
					ug.setPriceByWeight(goods.isWeighAble());
					ug.setBuyedPeopleCount(goods.getTotalSales());
					ug.setStock(goods.getStock());
					goodsList.add(ug);
				}
				Log.d("CEXX", "CEXX ---> getGoodsListByGoodsRecommendObjectId ---> goodsList : "
						+ (goodsList == null ? goodsList : goodsList.size()));

				final UIGoodsList uiGoodsList = new UIGoodsList();
				uiGoodsList.setTotalNum(totalNum);
				uiGoodsList.setUIGoodsList(goodsList);
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Log.d("CEXX", "CEXX ---> getGoodsListByGoodsRecommendObjectId ---> totalNum : "
								+ uiGoodsList.getTotalNum());
						listener.dataRetrieved(requestId, uiGoodsList);
					}
				});
			}
		});
	}
	
	public void getGoodsCvsStoreRecommend(final StoreInfo cvsStoreInfo, 
			final int requestId, final RetrieveDataListener listener) {
		Log.d("CEXX", "CEXX-getGoodsCvsStoreRecommend-cvsStoreInfo:" + cvsStoreInfo);
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				final List<Goods> tempGoodsList = new ArrayList<Goods>();
				try {
					checkIsInit();
					AVQuery<Goods> query = AVQuery.getQuery(Goods.class);
					query.whereEqualTo(Goods.ATTR_STOREID, cvsStoreInfo.getStoreid());
					query.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
					query.whereEqualTo(Goods.ATTR_ISRECOMMEND, true);
					// 按照更新时间来排序
					query.orderByDescending(Goods.ATTR_UPDATE_AT);
					query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
					tempGoodsList.addAll(query.find());
					Log.d("CEXX", "CEXX-getGoodsCvsStoreRecommend-tempGoodsList.size:" + tempGoodsList.size());
				} catch (Exception exception) {
					Log.d("CEXX", "CEXX-getGoodsCvsStoreRecommend-exception:" + exception.toString());
				}

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						final List<UIGoods> goodsList = new ArrayList<UIGoods>();
						for (Goods goods : tempGoodsList) {
							UIGoods ug = new UIGoods();
							ug.setStoreId(goods.getStoreId());
							ug.setObjectId(goods.getObjectId());
							ug.setDescroption(goods.getDescription());
							ug.setSpecs(goods.getSpecs());
							ug.setDiscount(goods.getDiscount());
							ug.setPicUrl(goods.getImageUrl());
							ug.setPriceAfterDiscount(goods.getRealPrice());
							ug.setShowTag(goods.getShowTag());
							ug.setUnit(goods.getUnit());
							ug.setStepUnit(goods.getWeighUnit());
							ug.setStep(goods.getWeighStep());
							ug.setPriceBeforeDiscount(goods.getPrice());
							ug.setPriceByWeight(goods.isWeighAble());
							ug.setBuyedPeopleCount(goods.getTotalSales());
							ug.setStock(goods.getStock());
							goodsList.add(ug);
						}

						Log.d("CEXX", "CEXX-getGoodsCvsStoreRecommend-goodsList.size:" + goodsList.size());
						listener.dataRetrieved(requestId, goodsList);
					}
				});
			}
		});
	}

	public void getRecommendByUs(final int sectionNum, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				final List<RecommendByUs> antTradeStyles = new ArrayList<RecommendByUs>();
				;

				AVQuery<RecommendByUs> query = AVQuery.getQuery(RecommendByUs.class);
				query.whereEqualTo(RecommendByUs.ATTR_SECTIONNUM, sectionNum);
				query.orderByDescending("updatedAt");
				query.limit(1000);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					antTradeStyles.addAll(query.find());
				} catch (AVException exception) {
					Log.e(TAG, "Query RecommendByUs failed.", exception);
				}

				final List<UIRecommendByUs> list = new ArrayList<UIRecommendByUs>();
				for (RecommendByUs rbu : antTradeStyles) {
					UIRecommendByUs urbu = new UIRecommendByUs();
					urbu.setObjectId(rbu.getObjectId());
					urbu.setShowIndex(rbu.getShowIndex());
					urbu.setTitleIconUrl(rbu.getIconUrl());
					urbu.setTitleDes(rbu.getTitle());
					list.add(urbu);
					Log.d("CEXX", "CEXX ---> getRecommendByUs ---> getTitleIconUrl : " + urbu.getTitleIconUrl());
					Log.d("CEXX", "CEXX ---> getRecommendByUs ---> getTitleDes : " + urbu.getTitleDes());
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Log.d("CEXX", "CEXX ---> getRecommendByUs ---> size : " + list.size());
						listener.dataRetrieved(requestId, list);
					}
				});
			}
		});
	}

	public void getGoodsByRecommendByUs(final String objectId, final int sectionNum, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				final AVQuery<RecommendByUs> query = AVQuery.getQuery(RecommendByUs.class);
				query.whereEqualTo("objectId", objectId);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				query.findInBackground(new FindCallback<RecommendByUs>() {
					@Override
					public void done(List<RecommendByUs> list, AVException e) {
						if (list != null && list.size() > 0) {
							AVRelation<Goods> relation = list.get(0).getRelation(RecommendByUs.ATTR_LIST);
							AVQuery<Goods> query1 = relation.getQuery();

							AVQuery<ServerSection> innerQuery = AVQuery.getQuery(ServerSection.class);
							innerQuery.whereEqualTo(ServerSection.ATTR_SECTIONNUM, sectionNum);
							query1.whereMatchesQuery(Goods.ATTR_UPTOWNS, innerQuery);
							query1.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
							query1.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
							query1.findInBackground(new FindCallback<Goods>() {
								@Override
								public void done(final List<Goods> list1, AVException e) {
									mHandler.post(new Runnable() {
										@Override
										public void run() {
											final List<UIGoods> goodsList = new ArrayList<UIGoods>();
											if (list1 != null) {
												for (Goods goods : list1) {
													UIGoods ug = new UIGoods();
													ug.setStoreId(goods.getStoreId());
													ug.setObjectId(goods.getObjectId());
													ug.setDescroption(goods.getDescription());
													ug.setSpecs(goods.getSpecs());
													ug.setDiscount(goods.getDiscount());
													ug.setPicUrl(goods.getImageUrl());
													ug.setPriceAfterDiscount(goods.getRealPrice());
													ug.setShowTag(goods.getShowTag());
													ug.setUnit(goods.getUnit());
													ug.setStepUnit(goods.getWeighUnit());
													ug.setStep(goods.getWeighStep());
													ug.setPriceBeforeDiscount(goods.getPrice());
													ug.setPriceByWeight(goods.isWeighAble());
													ug.setBuyedPeopleCount(goods.getTotalSales());
													ug.setStock(goods.getStock());
													goodsList.add(ug);
												}
											}

											Log.d("CEXX", "CEXX ---> getGoodsByRecommendByUs ---> size : "
													+ goodsList.size());
											listener.dataRetrieved(requestId, goodsList);
										}
									});

								}
							});
						} else {
							mHandler.post(new Runnable() {
								@Override
								public void run() {
									listener.dataRetrieved(requestId, null);
								}
							});
						}

					}
				});

			}
		});
	}

	public void getGoodsDetail(final String objectId, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
			    Log.d(TAG, "Query getGoodsDetail PROCESS1." );
				checkIsInit();
				Log.d(TAG, "Query getGoodsDetail PROCESS2." );
				AVQuery<Goods> query = AVQuery.getQuery(Goods.class);
				query.include(Goods.ATTR_UPTOWNS);
//				query.whereEqualTo(Goods.ATTR_OBJECID, objectId);
				Goods temp = null;
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
				    Log.d(TAG, "Query getGoodsDetail PROCESS3." );
				   
				    temp= query.get(objectId);
					Log.d(TAG, "Query getGoodsDetail success." + temp + " objectId:" + objectId);
				} catch (AVException exception) {
					Log.e(TAG, "Query getGoodsDetail failed.", exception);
				}
				final Goods result = temp;
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, result);
					}
				});
			}
		});
	}

	/**
	 * 根据分类名称获取商品列表，支持分页查询，返回对象为GoodsList,查询商品列表的时候需要携带区域号
	 * 
	 * @param style
	 * @param start
	 * @param expectCount
	 * @param sectionNum
	 * @param orderBy
	 *            按照排序0，销量；1：价格；2：更新时间
	 * @param storeId
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void getGoodsListByCategory(final String style, final int start, final int expectCount, final int sectionNum,
			final int orderBy, final String storeId, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<Goods> query = AVQuery.getQuery(Goods.class);

				if (TextUtils.isEmpty(storeId)) {
					AVQuery<ServerSection> innerQuery = AVQuery.getQuery(ServerSection.class);
					innerQuery.whereEqualTo(ServerSection.ATTR_SECTIONNUM, sectionNum);
					query.whereMatchesQuery(Goods.ATTR_UPTOWNS, innerQuery);
				} else {
					query.whereEqualTo(Goods.ATTR_STOREID, storeId);
				}
				query.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
				query.whereEqualTo(Goods.ATTR_STYLE, style);
				query.limit(expectCount);
				if (orderBy == 1) {
					// 按照更新时间来排序
					query.orderByAscending(Goods.ATTR_PRICE);
				} else if (orderBy == 2) {
					query.orderByDescending(Goods.ATTR_UPDATE_AT);
				} else {
					query.orderByDescending(Goods.ATTR_TOTAL_SALES);
				}
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				query.setSkip(start);
				GoodsList goodsList = new GoodsList();
				try {
					goodsList.setGoodList(query.find());
					goodsList.setTotalNum(query.count());
					iLog.d("query.count():" + goodsList.getTotalNum() + " " + goodsList.getGoodList().size());

					for (int i = 0; i < goodsList.getGoodList().size(); i++) {
						iLog.d("query.count(): detail:" + goodsList.getGoodList().get(i).getObjectId());
					}
				} catch (AVException exception) {
					iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
				}

				final UIGoodsList uiGoodsList = new UIGoodsList();
				uiGoodsList.setTotalNum(goodsList.getTotalNum());
				List<Goods> tempGoodsList = goodsList.getGoodList();
				if (tempGoodsList != null) {
					List<UIGoods> tempUIGoodsList = new ArrayList<UIGoods>();
					for (Goods goods : tempGoodsList) {
						UIGoods ug = new UIGoods();
						ug.setStoreId(goods.getStoreId());
						ug.setObjectId(goods.getObjectId());
						ug.setDescroption(goods.getDescription());
						ug.setSpecs(goods.getSpecs());
						ug.setDiscount(goods.getDiscount());
						ug.setPicUrl(goods.getImageUrl());
						ug.setPriceAfterDiscount(goods.getRealPrice());
						ug.setShowTag(goods.getShowTag());
						ug.setUnit(goods.getUnit());
						ug.setStepUnit(goods.getWeighUnit());
						ug.setStep(goods.getWeighStep());
						ug.setPriceBeforeDiscount(goods.getPrice());
						ug.setPriceByWeight(goods.isWeighAble());
						ug.setBuyedPeopleCount(goods.getTotalSales());
						ug.setStock(goods.getStock());
						tempUIGoodsList.add(ug);
					}
					uiGoodsList.setUIGoodsList(tempUIGoodsList);
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, uiGoodsList);
					}
				});
			}
		});
	}

	/**
	 * 查询所有的服务区域
	 * 
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void getServerSection(final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<ServerSection> query = AVQuery.getQuery(ServerSection.class);
				List<ServerSection> tempServerSection = null;
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					tempServerSection = query.find();
				} catch (AVException exception) {
					Log.e(TAG, "Query getServerSection failed.", exception);
				}

				// final List<UIServerSection> list = new
				// ArrayList<UIServerSection>();
				// if (tempServerSection != null)
				// {
				// for (ServerSection serverSection : tempServerSection)
				// {
				// UIServerSection uss = new UIServerSection();
				// uss.setArea(serverSection.getArea());
				// uss.setCity(serverSection.getCity());
				// uss.setObjectId(serverSection.getObjectId());
				// uss.setSectionNum(serverSection.getSectionnum());
				// uss.setUpTown(serverSection.getUptown());
				// uss.setShowCartStoreId(serverSection.getShowCartStoreId());
				// uss.setPickupStation(serverSection.getPickupStation());
				// list.add(uss);
				// }
				// }

				if (tempServerSection == null) {
					tempServerSection = new ArrayList<ServerSection>();
				}
				final List<ServerSection> list = tempServerSection;
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Log.d("CEXX", "CEXX ---> getServerSection ---> size : " + list.size());
						listener.dataRetrieved(requestId, list);
					}
				});
			}
		});
	}

	public void getServerSectionById(final String objectId, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<ServerSection> query = AVQuery.getQuery(ServerSection.class);
				List<ServerSection> tempServerSection = null;
				query.whereEqualTo(ServerSection.ATTR_OBJECID, objectId);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					tempServerSection = query.find();
				} catch (AVException exception) {
					Log.e(TAG, "Query getServerSectionById failed.", exception);
				}

				if (tempServerSection == null) {
					tempServerSection = new ArrayList<ServerSection>();
				}
				final List<ServerSection> list = tempServerSection;
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Log.d("CEXX", "CEXX ---> getServerSectionById ---> size : " + list.size());
						listener.dataRetrieved(requestId, list);
					}
				});
			}
		});
	}

	public void getFavGoodsList(final String usrId, final int sectionNum, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<MyFavorite> query = AVQuery.getQuery(MyFavorite.class);

				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				query.whereEqualTo(MyFavorite.ATTR_USRID, usrId);
				// 按照更新时间来排序

				final GoodsList goodsList = new GoodsList();
				try {
					MyFavorite myFavorite = query.getFirst();
					AVRelation<Goods> relation = myFavorite.getRelation(MyFavorite.ATTR_RELATIONITEMS);
					AVQuery<Goods> query1 = relation.getQuery();
					query1.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
					goodsList.setGoodList(query1.find());

				} catch (AVException exception) {
					iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
				}

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, goodsList);
					}
				});
			}
		});
	}

	/**
	 * 查询用户的购物车
	 * 
	 * @param usrId
	 * @param sectionNum
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void getShoppingCart(final String usrId, final int sectionNum, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<ShoppingCart> query = AVQuery.getQuery(ShoppingCart.class);
				query.whereEqualTo(ShoppingCart.ATTR_USERID, usrId);
				query.whereEqualTo(ShoppingCart.ATTR_SECTIONNUM, sectionNum);
				// 按照更新时间来排序
				query.orderByDescending(Goods.ATTR_UPDATE_AT);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				final List<ShoppingCart> goodsList = new ArrayList<ShoppingCart>();
				try {
					goodsList.addAll(query.find());

				} catch (AVException exception) {
					iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
				}
				if (goodsList != null && goodsList.size() > 0) {
					List<String> goodsIds = new ArrayList<String>();
					HashMap<String, ShoppingCart> carts = new HashMap<String, ShoppingCart>();
					for (int i = 0; i < goodsList.size(); i++) {
						ShoppingCart shoppingCart = goodsList.get(i);
						goodsIds.add(shoppingCart.getGoodsid());
						carts.put(shoppingCart.getGoodsid(), shoppingCart);
					}

					try {
						AVQuery<Goods> queryGoods = AVQuery.getQuery(Goods.class);
						queryGoods.whereContainedIn(Goods.ATTR_OBJECID, goodsIds);
						List<Goods> tempGoods = queryGoods.find();
						if (tempGoods != null && tempGoods.size() > 0) {
							for (int i = 0; i < tempGoods.size(); i++) {
								Goods goods = tempGoods.get(i);
								carts.get(goods.getObjectId()).setGoods(goods);
							}
							for (ShoppingCart sc : goodsList) {
								if (sc.getGoods() == null) {
									sc.setGoods(new Goods());
								}
							}
							mHandler.post(new Runnable() {
								@Override
								public void run() {
									listener.dataRetrieved(requestId, goodsList);
								}
							});
							return;
						} else {

						}
						Log.d(TAG, "getShoppingCart tempGoods:" + tempGoods);
					} catch (AVException e) {
						e.printStackTrace();
					}
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, goodsList);
					}
				});

			}
		});
	}
	
	public void clearShoppingCart(final String usrId, final int sectionNum) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					AVQuery<ShoppingCart> query = AVQuery.getQuery(ShoppingCart.class);
					query.whereEqualTo(ShoppingCart.ATTR_USERID, usrId);
					query.whereEqualTo(ShoppingCart.ATTR_SECTIONNUM, sectionNum);
					query.deleteAll();
				} catch (AVException e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 添加商品到购物车
	 * 
	 * @param usrId
	 * @param sectionNum
	 * @param goods
	 * @param quantity
	 * @param requestId
	 * @param listener：返回object的对象为空时表示错误，不为空时，表示成功
	 * @since 3.8
	 */
	public void addToShoppingCart(final String usrId, final int sectionNum, final Goods goods, final double quantity,
			final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				if (TextUtils.isEmpty(usrId) || goods == null) {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
					return;
				}
				final ShoppingCart shoppingCart = new ShoppingCart();
				shoppingCart.setGoods(goods);
				shoppingCart.setGoodsid(goods.getObjectId());
				shoppingCart.setSectionNum(sectionNum);
				shoppingCart.setStyle(goods.getStyle());
				shoppingCart.setStoreId(goods.getStoreId());
				shoppingCart.setUserId(usrId);
				DecimalFormat df = new DecimalFormat("#########.##");
				if (goods.getDiscount() < 0.00001) {
					shoppingCart.setCost(quantity * goods.getPrice());
				} else {
					shoppingCart.setCost(quantity * goods.getPrice() * goods.getDiscount() / 10);
				}

				shoppingCart.setQuantity(quantity);

				try {
					shoppingCart.save();
					AntHomeApplication.shoppingMap.put(shoppingCart.getGoodsid(), shoppingCart);
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, shoppingCart);
						}
					});
				} catch (AVException e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 删除购物车中的商品
	 * 
	 * @param usrId
	 * @param sectionNum
	 * @param goods
	 * @param quantity
	 * @param requestId
	 * @param listener：返回object的对象为空时表示错误，不为空时，表示成功
	 * @since 3.8
	 */
	public void removeShoppingCart(final ShoppingCart shoppingCart, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();

				try {
					shoppingCart.delete();
					AntHomeApplication.shoppingMap.remove(shoppingCart.getGoodsid());
					Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
					AntHomeApplication.context.sendBroadcast(intent);
					if (listener != null) {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								listener.dataRetrieved(requestId, new Object());
							}
						});
					}
				} catch (AVException e) {
					e.printStackTrace();
					if (listener != null) {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								listener.dataRetrieved(requestId, null);
							}
						});
					}
				}

			}
		});
	}

	/**
	 * 更新购物车中的商品
	 * 
	 * @param usrId
	 * @param sectionNum
	 * @param goods
	 * @param quantity
	 * @param requestId
	 * @param listener：返回object的对象为空时表示错误，不为空时，表示成功
	 * @since 3.8
	 */
	public void updateShoppingCart(final ShoppingCart shoppingCart, final String userId, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {

					AVQuery<ShoppingCart> query = AVQuery.getQuery(ShoppingCart.class);
					query.whereEqualTo(ShoppingCart.ATTR_USERID, userId);
					query.whereEqualTo(ShoppingCart.ATTR_SECTIONNUM, shoppingCart.getSectionNum());
					query.whereEqualTo(ShoppingCart.ATTR_GOODSID, shoppingCart.getGoodsid());
					final ShoppingCart serverShoppingCart = query.getFirst();

					Goods goods = shoppingCart.getGoods();
					double quantity = shoppingCart.getQuantity();
					if (goods.getDiscount() < 0.00001) {
						shoppingCart.setCost(quantity * goods.getPrice());
					} else {
						shoppingCart.setCost(quantity * goods.getPrice() * goods.getDiscount() / 10);
					}
					serverShoppingCart.setQuantity(quantity);
					serverShoppingCart.setCost(shoppingCart.getCost());
					serverShoppingCart.save();
					serverShoppingCart.setGoods(goods);
					AntHomeApplication.shoppingMap.put(shoppingCart.getGoodsid(), serverShoppingCart);
					Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
					AntHomeApplication.context.sendBroadcast(intent);
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, serverShoppingCart);
						}
					});
				} catch (AVException e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 添加到收藏
	 * 
	 * @param goodsId
	 * @param userId
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void addToFav(final String goodsId, final String userId, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {

					final AVQuery<MyFavorite> query = AVQuery.getQuery(MyFavorite.class);
					query.whereEqualTo("userId", userId);
					List<MyFavorite> list = query.find();
					Goods goods = AVQuery.getQuery(Goods.class).get(goodsId);
					if (list != null && list.size() > 0) {
						AVRelation<Goods> relation = list.get(0).getRelation(MyFavorite.ATTR_RELATIONITEMS);
						relation.add(goods);
						list.get(0).save();
					} else {
						MyFavorite myFavorite = new MyFavorite();
						myFavorite.setUserId(userId);
						AVRelation<AVObject> relation = myFavorite.getRelation(MyFavorite.ATTR_RELATIONITEMS);
						relation.add(goods);
						myFavorite.save();
					}

					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, new Object());
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 取消收藏
	 * 
	 * @param goodsId
	 * @param userId
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void cancelFav(final String goodsId, final String userId, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {

					final AVQuery<MyFavorite> query = AVQuery.getQuery(MyFavorite.class);
					query.whereEqualTo("userId", userId);
					List<MyFavorite> list = query.find();
					Goods goods = AVQuery.getQuery(Goods.class).get(goodsId);
					if (list != null && list.size() > 0) {
						AVRelation<Goods> relation = list.get(0).getRelation(MyFavorite.ATTR_RELATIONITEMS);
						relation.remove(goods);
						list.get(0).save();
					}
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, new Object());
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 添加用户地址
	 * 
	 * @param userId
	 * @param name
	 * @param mobilephone
	 * @param uptown
	 * @param door
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void addAddress(final String userId, final String name, final String mobilephone, final String uptown,
			final String door, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {

					final ShippingAddr address = new ShippingAddr();
					address.setUserId(userId);
					address.setDoor(door);
					address.setMobile(mobilephone);
					address.setUptown(uptown);
					address.setName(name);
					address.save();

					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, address);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 更新用户地址,设置为默认地址时也调用这个接口
	 * 
	 * @param userId
	 * @param name
	 * @param mobilephone
	 * @param uptown
	 * @param door
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void updateAddress(final String objectId, final String userId, final String name, final String mobilephone,
			final String uptown, final String door, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					final AVQuery<ShippingAddr> query = AVQuery.getQuery(ShippingAddr.class);

					final ShippingAddr address = query.get(objectId);
					address.setUserId(userId);
					address.setDoor(door);
					address.setMobile(mobilephone);
					address.setUptown(uptown);
					address.setName(name);
					address.save();

					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, address);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 删除地址
	 * 
	 * @param objectId
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void deleteAddress(final String objectId, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					final AVQuery<ShippingAddr> query = AVQuery.getQuery(ShippingAddr.class);

					final ShippingAddr address = query.get(objectId);
					address.delete();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, address);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 获取地址列表：第一个为默认地址
	 * 
	 * @param objectId
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void getAddressList(final String userId, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					final AVQuery<ShippingAddr> query = AVQuery.getQuery(ShippingAddr.class);
					query.whereEqualTo(ShippingAddr.ATTR_USERID, userId);
					query.orderByDescending(ShippingAddr.ATTR_UPDATE_AT);
					query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
					final List<ShippingAddr> list = query.find();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, list);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 根据订单类型，获取对应订单
	 * 
	 * @param userId
	 * @param orderTypes
	 * @param requestId
	 * @param listener
	 * @since 3.8
	 */
	public void getMyOrderByType(final String userId, final int orderType, final int start, final int expectedCount,
			final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					final AVQuery<Order> query = AVQuery.getQuery(Order.class);
					query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
					if (orderType != Order.ORDER_TYPE_ALL) {
						if (orderType == OrdersListFragment.ORDER_TYPE_UNRECEIVE) {
							ArrayList<Integer> orderTypes = new ArrayList<Integer>();
							orderTypes.add(OrderStatusCode.ORDER_WAIT_FOR_SIGN.value());
							orderTypes.add(OrderStatusCode.ORDER_SHIPPED.value());
							orderTypes.add(OrderStatusCode.ORDER_2_STATION.value());
							query.whereEqualTo(Order.ATTR_HASPAY, 1);
							query.whereContainedIn(Order.ATTR_STATUSCODE, orderTypes);
						} else if (orderType == OrdersListFragment.ORDER_TYPE_UNSEND) {

							ArrayList<Integer> orderTypes = new ArrayList<Integer>();
							orderTypes.add(OrderStatusCode.ORDER_PENDING.value());
							orderTypes.add(OrderStatusCode.ORDER_WEIGHED.value());
							query.whereEqualTo(Order.ATTR_HASPAY, 1);
							query.whereContainedIn(Order.ATTR_STATUSCODE, orderTypes);
							
						}
						else if (orderType == OrdersListFragment.ORDER_TYPE_UNPAY) {

							ArrayList<Integer> orderTypes = new ArrayList<Integer>();
							orderTypes.add(OrderStatusCode.ORDER_WEIGHED.value());
							orderTypes.add(OrderStatusCode.ORDER_WAIT_FOR_PAY.value());
							orderTypes.add(OrderStatusCode.ORDER_PENDING.value());
							orderTypes.add(OrderStatusCode.ORDER_UN_WEIGHED.value());
							query.whereEqualTo(Order.ATTR_HASPAY, 0);
							query.whereContainedIn(Order.ATTR_STATUSCODE, orderTypes);
						}
						
						else {
							query.whereEqualTo(Order.ATTR_STATUSCODE, orderType);
						}

					}
					query.setSkip(start);
					query.limit(expectedCount);
					query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);

					query.orderByDescending(Order.ATTR_CREATED_AT);
					// query.orderByAscending(Order.ATTR_STATUSCODE);

					final OrderList orderList = new OrderList();
					orderList.setOrderList(query.find());
					orderList.setTotalNum(query.count());

					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, orderList);
						}
					});
				} catch (Exception e) {
					iLog.e(TAG, "getMyOrderByType", e);
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 创建订单
	 * 
	 * @param userId
	 * @param shoppingCart
	 * @param shippingAddr
	 * @param customerComment
	 * @param deliveryTime
	 * @param requestId
	 * @param listener
	 */
	public void makeOrder(final String userId, final List<ShoppingCart> uiShoppingCart, final ShippingAddr shippingAddr,
			final String customerComment, final Date deliveryTime, final String payWay, final String deliveryWay,
			final double deliveryCost, final boolean isSP, final String pickUpStationId, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					// Order order=new Order();
					final AVObject order = new AVObject(AntAVObject.CLASS_ORDER);
					order.put(Order.ATTR_ADDRESS, shippingAddr.getUptown() + shippingAddr.getDoor());
					order.put(Order.ATTR_CUSTOMREMARK, customerComment);
					order.put(Order.ATTR_CONSIGNEE, shippingAddr.getName());
					order.put(Order.ATTR_PHONE, shippingAddr.getMobile());
					order.put(Order.ATTR_CUSTOMID, userId);
					order.put(Order.ATTR_DELIVERYWAY, deliveryWay);
					order.put(Order.ATTR_PICKUPSTATIONID, pickUpStationId);
					order.put(Order.ATTR_DELIVERYCOST, deliveryCost);
					if (isSP) {
						order.put(Order.ATTR_ORDERTYPE, Order.STORE_TYPE_SP);
						order.put(Order.ATTR_SECTIONNUM, AntHomeApplication.sectionNum);
					} else {
						order.put(Order.ATTR_ORDERTYPE, Order.STORE_TYPE_SINGLE);

					}

					long current = System.currentTimeMillis();
					SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
					order.put(Order.ATTR_DELIVERYTIME, deliveryTime);
					Date date = new Date();
					date.setTime(current);
					order.put(Order.ATTR_PAYWAY, payWay);

					if (uiShoppingCart != null && uiShoppingCart.size() > 0) {
						List<OrderItem> orderItems = new ArrayList<OrderItem>();
						JSONArray array = new JSONArray();
						boolean isHaveWeight = false;
						for (int i = 0; i < uiShoppingCart.size(); i++) {
							OrderItem orderItem = new OrderItem();

							orderItem.setGoodsId(uiShoppingCart.get(i).getGoodsid());
							Goods goods = uiShoppingCart.get(i).getGoods();
							orderItem.setPicUrl(goods.getImageUrl());
							orderItem.setQuantity(uiShoppingCart.get(i).getQuantity());
							orderItem.setName(goods.getDescriptionAndSpecs());
							// 保存的价格为折扣价格
							if (goods.getDiscount() < 0.00001) {
								orderItem.setPrice(goods.getPrice());
							} else {
								orderItem.setPrice(goods.getPrice() * goods.getDiscount() / 10);
							}
							// 根据是否为称重保存单个item的总价
							if (goods.isWeighAble()) {
								orderItem.setCost(0);
								isHaveWeight = true;
							} else {
								orderItem.setCost(orderItem.getQuantity() * orderItem.getPrice());
							}

							orderItem.setUnit(goods.getUnit());
							orderItem.setWeighAble(goods.isWeighAble());
							orderItem.setWeighUnit(goods.getWeighUnit());

							String storeId = uiShoppingCart.get(i).getStoreId();
							if (TextUtils.isEmpty(storeId)) {
								storeId = goods.getStoreId();
							} else {

							}
							order.put(Order.ATTR_STOREID, storeId);

							orderItems.add(orderItem);
							array.put(orderItem.convertToJson());
						}

						String totalCost = UtilTools.getTotalCostByOrderItems(orderItems);
						double totalCostMoney = Double.parseDouble(totalCost);
						
						order.put(Order.ATTR_ORDERITEMS, array.toString());

						if (order.get(Order.ATTR_STOREID) != null) {
							StoreInfo storeInfo = AntHomeApplication.storeInfos
									.get(order.get(Order.ATTR_STOREID).toString());
							if (storeInfo != null) {

								if (!isHaveWeight) {
									if (totalCostMoney > storeInfo.getStartcost()) {
										order.put(Order.ATTR_DELIVERYCOST, 0);
									} else {
										order.put(Order.ATTR_DELIVERYCOST, storeInfo.getDeliverycost());
									}
								}
								// 商店支持减免
								if (storeInfo.isHaveDisaccount()) {
									AVUser user = AVUser.getCurrentUser();

									if (user != null) {
										// 是否已经使用过首单减免
										boolean isused = user.getBoolean("firstOrderDiscountUsed");
										if (!isused) {
											// 没使用的话到服务器在实时查询
											AVQuery<AVUser> query = AVUser.getQuery();
											AVUser userTemp = query.get(userId);
											boolean isUserTemp = userTemp.getBoolean("firstOrderDiscountUsed");
											if (!isUserTemp) {
												if (totalCostMoney > storeInfo.getFirstOrderLimit()) {
													order.put(Order.ATTR_FAVORABLECOST,
															storeInfo.getFirstOrderDiscount());
													userTemp.put("firstOrderDiscountUsed", true);
													userTemp.saveInBackground();
												}
											}
										}
									}
								}
							}
						}
						if(AntHomeApplication.context.getResources().getString(R.string.order_ensure_send_metho_ziting).equals(deliveryWay))
						{
							order.put(Order.ATTR_DELIVERYCOST, 0);	
						}

						
						//计算总金额
						
						double realTotalCost=totalCostMoney+order.getDouble(Order.ATTR_DELIVERYCOST)-order.getDouble(Order.ATTR_FAVORABLECOST);
						order.put(Order.ATTR_TOTALCOST, realTotalCost);
						
					}

					

					AVCloud.setProductionMode(false);
					Map<String, Object> parameters = new HashMap<String, Object>();
					parameters.put("object", order);
					AVCloud.callFunctionInBackground("beforeSave", parameters, new FunctionCallback<AVObject>() {
						public void done(AVObject object, AVException e) {
							if (e == null) {
								// processResponse(object);
								// object.saveInBackground();
							} else {
								// handleError();
							}
						}
					});
					// order.saveInBackground();
					// 保存完毕之后获取最新数值
					order.setFetchWhenSave(true);
					order.save();
					/**
					 * 创建订单之后需要更新购物车数量
					 */
					if (uiShoppingCart != null && uiShoppingCart.size() > 0) {
						for (int i = 0; i < uiShoppingCart.size(); i++) {

							AntHomeApplication.shoppingMap.remove(uiShoppingCart.get(i).getGoodsid());
						}
						Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
						AntHomeApplication.context.sendBroadcast(intent);
					}
					
					// TODO 订单创建完毕之后发送通知给店铺端,商店ID即为用户的objectId
					final String storeId = order.getString(Order.ATTR_STOREID);
					if (!TextUtils.isEmpty(storeId)) {
						AVQuery<AVUser> query = AVUser.getQuery();
						query.getInBackground(storeId, new GetCallback<AVUser>() {

							@Override
							public void done(AVUser arg0, AVException arg1) {

								if (arg1 == null && arg0 != null) {
									AVUser avUser = arg0;
//	storeId:558e14bae4b060308e3d465e installId:null orderId:5957571963 avUser:sp31

									String installId = avUser.getString(Const.AVUSER_KEY_INSTALLID);
									iLog.d("storeId:" + storeId + " installId:" + installId + " orderId:"
											+ order.getString("orderId") + " avUser:" + avUser.getUsername());
									NotificationUtil.sendMsgToStore(
											AntHomeApplication.context.getString(R.string.orderdetail_hint,
													order.getString("orderId")),
											order.getString("orderId"), MyMsg.MSG_TYPE_ORDERDETAIL, installId, storeId);
								}
							}
						});
					}
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId,order);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 关闭订单
	 * 
	 * @param userId
	 * @param shoppingCart
	 * @param shippingAddr
	 * @param customerComment
	 * @param deliveryTime
	 * @param expectedCount
	 * @param requestId
	 * @param listener
	 */
	public void closeOrder(final String userId, final String orderId, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					final AVQuery<Order> query = AVQuery.getQuery(Order.class);
					query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
					query.whereEqualTo(Order.ATTR_ORDERID, orderId);
					Order order = query.getFirst();
					order.setStatusCode(OrderStatusCode.ORDER_CLOSED.value());
					order.save();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, new Object());
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 修改订单状态
	 * 
	 * @param userId
	 * @param shoppingCart
	 * @param shippingAddr
	 * @param customerComment
	 * @param deliveryTime
	 * @param expectedCount
	 * @param requestId
	 * @param listener
	 */
	public void updateOrder(final String userId, final String orderId, final int status, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					final AVQuery<Order> query = AVQuery.getQuery(Order.class);
					query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
					query.whereEqualTo(Order.ATTR_ORDERID, orderId);
					Order order = query.getFirst();
					order.setStatusCode(status);
					if(OrderStatusCode.ORDER_SIGNED.value()==status)
					{
					    Date date = new Date();
			            date.setTime(System.currentTimeMillis());
			            order.setSignedTime(date);  
					}
					order.save();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, new Object());
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

	/**
	 * 查询商品
	 * 
	 * @param keyWord
	 * @param sectionNum
	 * @param storeId
	 *            独立商店的ID，为空时则认为不是独立商店
	 * @param requestId
	 * @param listener
	 */
	public void searchGoodsList(final String keyWord, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				final List<Goods> temp = new ArrayList<Goods>();
				
				AVQuery<Goods> query = AVQuery.getQuery(Goods.class);
				query.whereContains(Goods.ATTR_DESCRIPTION, keyWord);
				ServerSection serverSection = UtilTools.getServerSection(AntHomeApplication.context);
				AVQuery<ServerSection> innerQuery = AVQuery.getQuery(ServerSection.class);
				innerQuery.whereEqualTo(ServerSection.ATTR_OBJECID, serverSection.getObjectId());
				query.whereMatchesQuery(Goods.ATTR_UPTOWNS, innerQuery);
				query.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
				query.orderByDescending("updatedAt");
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					List<Goods> goods = query.find();
					temp.addAll(goods);
				} catch (AVException e1) {
					e1.printStackTrace();
				}
				iLog.d(TAG, "doCloudQueryInBackground:" + temp.size());
				
				if(AVUser.getCurrentUser() != null) {
					getStoreInfosForStore(-1, new RetrieveDataListener() {
						@Override
						public void dataRetrieved(int requestId2, final Object data) {
							mExecutorService.submit(new Runnable() {
								@Override
								public void run() {
									if(data != null) {
										StoreInfo cvsStoreInfo = (StoreInfo) data;
										AVQuery<Goods> queryCvs = AVQuery.getQuery(Goods.class);
										queryCvs.whereContains(Goods.ATTR_DESCRIPTION, keyWord);
										queryCvs.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
										queryCvs.whereEqualTo(Goods.ATTR_STOREID, cvsStoreInfo.getStoreid());
										queryCvs.orderByDescending("updatedAt");
										queryCvs.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
										try {
											List<Goods> goods = queryCvs.find();
											temp.addAll(goods);
										} catch (AVException e1) {
											e1.printStackTrace();
										}
									}
									
									final List<UIGoods> uiGoodsList = new ArrayList<UIGoods>();
									for (Goods goods : temp) {
										UIGoods ug = new UIGoods();
										ug.setStoreId(goods.getStoreId());
										ug.setObjectId(goods.getObjectId());
										ug.setDescroption(goods.getDescription());
										ug.setSpecs(goods.getSpecs());
										ug.setDiscount(goods.getDiscount());
										ug.setPicUrl(goods.getImageUrl());
										ug.setPriceAfterDiscount(goods.getRealPrice());
										ug.setShowTag(goods.getShowTag());
										ug.setUnit(goods.getUnit());
										ug.setStepUnit(goods.getWeighUnit());
										ug.setStep(goods.getWeighStep());
										ug.setPriceBeforeDiscount(goods.getPrice());
										ug.setPriceByWeight(goods.isWeighAble());
										ug.setBuyedPeopleCount(goods.getTotalSales());
										ug.setStock(goods.getStock());
										uiGoodsList.add(ug);
									}
									mHandler.post(new Runnable() {
										@Override
										public void run() {
											listener.dataRetrieved(requestId, uiGoodsList);
										}
									});
								}
							});
						}
					});
				} else {
					final List<UIGoods> uiGoodsList = new ArrayList<UIGoods>();
					for (Goods goods : temp) {
						UIGoods ug = new UIGoods();
						ug.setStoreId(goods.getStoreId());
						ug.setObjectId(goods.getObjectId());
						ug.setDescroption(goods.getDescription());
						ug.setSpecs(goods.getSpecs());
						ug.setDiscount(goods.getDiscount());
						ug.setPicUrl(goods.getImageUrl());
						ug.setPriceAfterDiscount(goods.getRealPrice());
						ug.setShowTag(goods.getShowTag());
						ug.setUnit(goods.getUnit());
						ug.setStepUnit(goods.getWeighUnit());
						ug.setStep(goods.getWeighStep());
						ug.setPriceBeforeDiscount(goods.getPrice());
						ug.setPriceByWeight(goods.isWeighAble());
						ug.setBuyedPeopleCount(goods.getTotalSales());
						ug.setStock(goods.getStock());
						uiGoodsList.add(ug);
					}
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, uiGoodsList);
						}
					});
				}
			}
		});
	}

	/**
	 * 启动的时候获取所有的商店信息
	 * 
	 * @param requestId
	 * @param listener
	 */
	public void getStoreInfos(final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<StoreInfo> query = AVQuery.getQuery(StoreInfo.class);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					List<StoreInfo> temp = query.find();
					if (temp != null && temp.size() > 0) {
						AntHomeApplication.storeInfos.clear();
						for (int i = 0; i < temp.size(); i++) {
							AntHomeApplication.storeInfos.put(temp.get(i).getStoreid(), temp.get(i));
						}
						Log.d(TAG, "AntHomeApplication.storeInfos:" + temp.size());
					}
				} catch (AVException e) {
					e.printStackTrace();
				}

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						if (listener != null) {
							listener.dataRetrieved(requestId, new Object());
						}

					}
				});
			}
		});
	}

	public void getStoreInfosForStore(final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				String tempCvsId = "";
				if(AVUser.getCurrentUser() != null) {
					tempCvsId = AVUser.getCurrentUser().getString(ServerSection.ATTR_CVSID);
					Log.d("CEXX", "CEXX > getStoreInfosForStore > tempCvsId 00 : " + tempCvsId);
				}
				
				if(TextUtils.isEmpty(tempCvsId)) {
					tempCvsId = UtilTools.getServerSection(AntHomeApplication.context).getCvsid();
					Log.d("CEXX", "CEXX > getStoreInfosForStore > tempCvsId 01 : " + tempCvsId);
				}
				
				tempCvsId = (tempCvsId==null ? "" : tempCvsId);
				final String cvsid = tempCvsId;
				Log.d("CEXX", "CEXX > getStoreInfosForStore > cvsid : " + cvsid);
				if (AntHomeApplication.storeInfos == null || AntHomeApplication.storeInfos.size() == 0) {
					RetrieveDataAsyn.getInstance().getStoreInfos(-1, new RetrieveDataListener() {
						@Override
						public void dataRetrieved(int requestId2, Object data) {
							StoreInfo cvsStoreInfo = null;
							if (AntHomeApplication.storeInfos != null && AntHomeApplication.storeInfos.size() >= 0) {
								// 获取到StoreInfo数据
								Collection<StoreInfo> storeInfos = AntHomeApplication.storeInfos.values();
								for (StoreInfo storeInfo : storeInfos) {
									if (cvsid.equals(storeInfo.getObjectId())) {
										cvsStoreInfo = storeInfo;
										break;
									}
								}
							}
							
							Log.d("CEXX", "CEXX > getStoreInfosForStore > cvsStoreInfo : " + cvsStoreInfo);
							final StoreInfo resultStoreInfo = cvsStoreInfo;
							if(listener != null) {
								mHandler.post(new Runnable() {
									@Override
									public void run() {
										listener.dataRetrieved(requestId, resultStoreInfo);
									}
								});
							}
						}
					});
				} else {
					// 获取到StoreInfo数据
					StoreInfo cvsStoreInfo = null;
					Collection<StoreInfo> storeInfos = AntHomeApplication.storeInfos.values();
					for (StoreInfo storeInfo : storeInfos) {
						if (cvsid.equals(storeInfo.getObjectId())) {
							cvsStoreInfo = storeInfo;
							break;
						}
					}
					
					Log.d("CEXX", "CEXX > getStoreInfosForStore > cvsStoreInfo : " + cvsStoreInfo);
					final StoreInfo resultStoreInfo = cvsStoreInfo;
					if(listener != null) {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								listener.dataRetrieved(requestId, resultStoreInfo);
							}
						});
					}
				}
			}
		});
	}
	
	/**
	 * 评论&反馈
	 * 
	 * @param requestId
	 * @param listener
	 * @return 返回对象为空的时候，保存不成功；不为空则成功
	 */
	public void commentFeedback(final String userId, final String comment, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				Evaluate evaluate = new Evaluate();
				evaluate.setUserId(userId);
				evaluate.setComment(comment);
				try {
					evaluate.save();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							if (listener != null) {
								listener.dataRetrieved(requestId, new Object());
							}

						}
					});
				} catch (AVException e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							if (listener != null) {
								listener.dataRetrieved(requestId, null);
							}

						}
					});
				}

			}
		});
	}

	/**
	 * 查询订单详情
	 * 
	 * @param objectId
	 * @param requestId
	 * @param listener
	 */
	public void getOrderDetail(final String objectId, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<Order> query = AVQuery.getQuery(Order.class);
				Order temp = null;
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					temp = query.get(objectId);
					Log.d(TAG, "Query getOrderDetail success." + temp + " objectId:" + objectId);
				} catch (AVException exception) {
					Log.e(TAG, "Query getOrderDetail failed.", exception);
				}
				final Order result = temp;
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, result);
					}
				});
			}
		});
	}

	/**
	 * 检查更新
	 * 
	 * @since 3.8
	 */
	public VersionInfo checkUpdate() {
		checkIsInit();
		AVQuery<VersionInfo> query = AVQuery.getQuery(VersionInfo.class);
		VersionInfo temp = null;
		query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
		query.orderByDescending("updatedAt");
		try {
			temp = query.getFirst();
		} catch (AVException e) {
			e.printStackTrace();
		}
		return temp;
	}

	/**
	 * 查询热词
	 * 
	 * @param requestId
	 * @param listener
	 */
	public void getHotWords(final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<HotWords> query = AVQuery.getQuery(HotWords.class);
				List<HotWords> temp = null;
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					temp = query.find();
				} catch (AVException exception) {
					Log.e(TAG, "Query getOrderDetail failed.", exception);
				}
				final List<HotWords> result = temp;
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, result);
					}
				});
			}
		});
	}

	public void getGoodsKind(final String storeId, final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				final List<GoodsKind> goodsKindList = new ArrayList<GoodsKind>();

				AVQuery<GoodsKind> query = AVQuery.getQuery(GoodsKind.class);
				query.whereEqualTo(GoodsKind.ATTR_USERID, storeId);
				query.orderByAscending("showIndex");
				query.include(GoodsKind.ATTR_STYLELIST);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				try {
					goodsKindList.addAll(query.find());
				} catch (AVException exception) {
					Log.e(TAG, "Query AntTradeStyle failed.", exception);
				}

				if (goodsKindList != null && goodsKindList.size() > 0) {
					for (int i = 0; i < goodsKindList.size(); i++) {
						GoodsKind goodsKind = goodsKindList.get(i);
						AVRelation<GoodsStyles> relation = goodsKind.getRelation(GoodsKind.ATTR_STYLELIST);
						AVQuery<GoodsStyles> query1 = relation.getQuery();
						try {
							goodsKind.setGoodsStylesList(query1.find());
						} catch (AVException e) {
							e.printStackTrace();
						}
					}
				}
				
				// 过滤掉没有商品的大类、小类
				List<GoodsKind> tempGkList = new ArrayList<GoodsKind>();
				for(GoodsKind gk : goodsKindList) {
					 List<GoodsStyles> gsList = gk.getGoodsStylesList();
					 if(gsList == null || gsList.size() == 0) {
						 tempGkList.add(gk);
						 continue;
					 } else {
						 boolean needHideKind = true;
						 List<GoodsStyles> tempGsList = new ArrayList<GoodsStyles>();
						 for(GoodsStyles gs : gsList) {
							 try {
								 String kind = gk.getName();
								 String style = gs.getName();
								 AVQuery<Goods> goodsQuery = AVQuery.getQuery(Goods.class);
								 goodsQuery.whereEqualTo(Goods.ATTR_STOREID, storeId);
								 goodsQuery.whereEqualTo(Goods.ATTR_KIND, kind);
								 goodsQuery.whereEqualTo(Goods.ATTR_STYLE, style);
								 goodsQuery.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
								 goodsQuery.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
								 int count = goodsQuery.count();
								 if(count > 0) {
									 needHideKind = false;
								 } else {
									 tempGsList.add(gs);
								 }
							} catch (AVException e) {
								e.printStackTrace();
							}
						 }
						 
						 gsList.removeAll(tempGsList);
						 if(needHideKind) {
							 tempGkList.add(gk);
						 }
					 }
				}
				goodsKindList.removeAll(tempGkList);

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, goodsKindList);
					}
				});
			}
		});
	}

	/**
	 * 根据大类、小类、storeId列表查询
	 * 
	 * @param kind
	 * @param style
	 * @param start
	 * @param expectCount
	 * @param storeIdList
	 * @param orderBy
	 *            按照排序0，销量；1：价格；2：更新时间
	 * @param requestId
	 * @param listener
	 */
	public void getGoodsListByKindAndStyle(final String kind, final String style, final int start,
			final int expectCount, final List<String> storeIdList, final int orderBy, final int requestId,
			final RetrieveDataListener listener) {
		Log.d("CEXX", "CEXX => getGoodsListByKindAndStyle => kind : " + kind);
		Log.d("CEXX", "CEXX => getGoodsListByKindAndStyle => style : " + style);
		Log.d("CEXX", "CEXX => getGoodsListByKindAndStyle => storeIdList : " + storeIdList);
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<Goods> query = AVQuery.getQuery(Goods.class);
				query.whereContainedIn(Goods.ATTR_STOREID, storeIdList);
				query.whereEqualTo(Goods.ATTR_IS_ON_SHELF, true);
				if (!TextUtils.isEmpty(kind)) {
					query.whereEqualTo(Goods.ATTR_KIND, kind);
				} else {
					// 如果kind为空，则认为是请求促销商品
					query.whereLessThan(Goods.ATTR_DISCOUNT, 10);
					query.whereGreaterThan(Goods.ATTR_DISCOUNT, 0);
				}

				if (!TextUtils.isEmpty(style)) {
					query.whereEqualTo(Goods.ATTR_STYLE, style);
				}
				query.limit(expectCount);
				if (orderBy == 1) {
					// 按照价格来排序
					query.orderByAscending(Goods.ATTR_PRICE);
				} else if (orderBy == 2) {
					// 按照更新时间来排序
					query.orderByDescending(Goods.ATTR_UPDATE_AT);
				} else {
					// 按照销量来排序
					query.orderByDescending(Goods.ATTR_TOTAL_SALES);
				}
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				query.setSkip(start);

				GoodsList goodsList = new GoodsList();
				try {
					goodsList.setGoodList(query.find());
					goodsList.setTotalNum(query.count());
					iLog.d("query.count():" + goodsList.getTotalNum() + " " + goodsList.getGoodList().size());

					for (int i = 0; i < goodsList.getGoodList().size(); i++) {
						iLog.d("query.count(): detail:" + goodsList.getGoodList().get(i).getObjectId());
					}
				} catch (AVException exception) {
					iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
				}

				final UIGoodsList uiGoodsList = new UIGoodsList();
				uiGoodsList.setTotalNum(goodsList.getTotalNum());
				List<Goods> tempGoodsList = goodsList.getGoodList();
				if (tempGoodsList != null) {
					List<UIGoods> tempUIGoodsList = new ArrayList<UIGoods>();
					for (Goods goods : tempGoodsList) {
						UIGoods ug = new UIGoods();
						ug.setStoreId(goods.getStoreId());
						ug.setObjectId(goods.getObjectId());
						ug.setDescroption(goods.getDescription());
						ug.setSpecs(goods.getSpecs());
						ug.setDiscount(goods.getDiscount());
						ug.setPicUrl(goods.getImageUrl());
						ug.setPriceAfterDiscount(goods.getRealPrice());
						ug.setShowTag(goods.getShowTag());
						ug.setUnit(goods.getUnit());
						ug.setStepUnit(goods.getWeighUnit());
						ug.setStep(goods.getWeighStep());
						ug.setPriceBeforeDiscount(goods.getPrice());
						ug.setPriceByWeight(goods.isWeighAble());
						ug.setBuyedPeopleCount(goods.getTotalSales());
						ug.setStock(goods.getStock());
						tempUIGoodsList.add(ug);
					}
					uiGoodsList.setUIGoodsList(tempUIGoodsList);
				}
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listener.dataRetrieved(requestId, uiGoodsList);
					}
				});
			}
		});
	}
	
	public void getEMRecvList(final int requestId, final RetrieveDataListener listener) {
		Log.d("CEXX", "CEXX > RetrieveDataAsyn > getEMRecvList");
		if(listener == null) {
			return;
		}
		
		final List<EMRecv> dataList = new ArrayList<EMRecv>();
		
		AVUser avUser = AVUser.getCurrentUser();
		if(avUser == null) {
			Log.d("CEXX", "CEXX > RetrieveDataAsyn > getEMRecvList 00");
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					listener.dataRetrieved(requestId, dataList);
				}
			});
			return;
		}
		
		final String userId = avUser.getObjectId();
		Log.d("CEXX", "CEXX > RetrieveDataAsyn > getEMRecvList > userId : " + userId);
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				final AVQuery<EMRecv> query = AVQuery.getQuery(EMRecv.class);
				query.whereEqualTo(EMRecv.ATTR_USERID, userId);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				List<EMRecv> emRecvList = null;
				try {
					emRecvList = query.find();
				} catch (AVException e) {
					e.printStackTrace();
				}
				if(emRecvList == null || emRecvList.size() == 0) {
					Log.d("CEXX", "CEXX > RetrieveDataAsyn > getEMRecvList 01");
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, dataList);
						}
					});
				} else {
					dataList.addAll(emRecvList);
					int size = emRecvList.size();
					Log.d("CEXX", "CEXX > RetrieveDataAsyn > getEMRecvList > size : " + size);
					for(int i=0; i<size; i++) {
						EMRecv emRecv = emRecvList.get(i);
						AVRelation<StoreInfo> storeRelation = emRecv.getRelation(EMRecv.ATTR_STORE);
						if(storeRelation == null) continue;
						AVQuery<StoreInfo> storeQuery = storeRelation.getQuery();
						if(storeQuery == null) continue;
						try {
							emRecv.setStore(storeQuery.getFirst());
						} catch (AVException e) {
							e.printStackTrace();
						}
					}
					
					for(int i=0; i<size; i++) {
						EMRecv emRecv = emRecvList.get(i);
						AVRelation<EMCompany> emCompanyRelation = emRecv.getRelation(EMRecv.ATTR_EMCOMPANY);
						if(emCompanyRelation == null) continue;
						AVQuery<EMCompany> emCompanyQuery = emCompanyRelation.getQuery();
						if(emCompanyQuery == null) continue;
						try {
							emRecv.setEMCompany(emCompanyQuery.getFirst());
						} catch (AVException e) {
							e.printStackTrace();
						}
					}
					
					Log.d("CEXX", "CEXX > RetrieveDataAsyn > getEMRecvList 02");
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, dataList);
						}
					});
				}
			}
		});
	}
}
